﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace AutoBuild.Core.Configuration

{
    public class WindsorConfiguration
    {
        //---- Members -----------------------------------------------------
        private readonly Assembly _coreAssembly;


        //---------------------------------------------------------
        public WindsorConfiguration()
        {
            _coreAssembly = typeof (AutoBuildRunner).Assembly;
        }

       
        //---------------------------------------------------------
        public virtual void ConfigureContainer(IWindsorContainer container)
        {

            container.Kernel.Resolver.AddSubResolver(new ArraySubDependencyResolver(container.Kernel));

            container
                .Register(Component
                              .For<AutoBuildRunner>()
                              .LifeStyle.Transient)
                .Register(Component
                              .For<FileSystemWatcher>()
                              .ImplementedBy<FileSystemWatcher>()
                              .LifeStyle.Transient);
            
            var assemblies = GetExtentionAssemblies();

            foreach (var extensionAssembly in assemblies)
            {
                container.Register(AllTypes.FromAssembly(extensionAssembly)
                                       .Where(t => t.GetInterfaces().Length > 0)
                                       .WithService.FirstInterface()
                                       .Configure(config => config.LifeStyle.Transient));

            }
        }

        //---------------------------------------------------------
        IEnumerable<Assembly> GetExtentionAssemblies()
        {
            var assemblies = new List<Assembly>(new [] {_coreAssembly});
            var path = Path.GetDirectoryName(_coreAssembly.CodeBase).Replace("file:\\", "");
            Assembly assembly;
            foreach (var file in Directory.GetFiles(path, "*AutoBuild.Runner*.dll"))
            {
                assembly = null;
                try
                {
                    assembly = Assembly.LoadFrom(file);
                }
                finally
                {
                    if (assembly != null)
                    {
                        assemblies.Add(assembly);
                    }
                }

            }
            return assemblies;
        }
    }
}